import React, { useEffect, useState } from 'react';
import { ProForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-components';
import { Card, message, Form, Button, Space, Input, Select, Checkbox, Tabs, Modal, List, Tag, Typography, Empty } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import api from '../../services/api';
import { Plugin, PluginParameter } from '../../types';
import { useTranslation } from 'react-i18next';

const { Text } = Typography;

const PluginForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [initialValues, setInitialValues] = useState<Partial<Plugin>>();
  const [parameters, setParameters] = useState<PluginParameter[]>([]);
  const [paramModalVisible, setParamModalVisible] = useState(false);
  const [editingParamIndex, setEditingParamIndex] = useState<number | null>(null);
  const [paramForm] = Form.useForm();
  const [form] = Form.useForm();
  const isEdit = !!id;

  useEffect(() => {
    if (isEdit) {
      fetchPlugin();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const fetchPlugin = async () => {
    try {
      const response = await api.get(`/plugins/${id}`);
      const pluginData = response.data;
      setInitialValues(pluginData);

      if (pluginData.parameterDefinitions) {
        const params = typeof pluginData.parameterDefinitions === 'string'
          ? JSON.parse(pluginData.parameterDefinitions)
          : pluginData.parameterDefinitions;
        setParameters(params || []);
      }

      form.setFieldsValue(pluginData);
    } catch (error: any) {
      message.error('Failed to fetch plugin details');
      navigate('/plugins');
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const payload = {
        ...values,
        parameterDefinitions: parameters.length > 0 ? parameters : null,
      };

      if (isEdit) {
        await api.put(`/plugins/${id}`, payload);
        message.success('Plugin updated successfully');
      } else {
        await api.post('/plugins/', payload);
        message.success('Plugin created successfully');
      }
      navigate('/plugins');
    } catch (error: any) {
      message.error(error.response?.data?.detail || `Failed to ${isEdit ? 'update' : 'create'} plugin`);
    } finally {
      setLoading(false);
    }
  };

  const handleOpenParamModal = (index?: number) => {
    if (index !== undefined) {
      const param = parameters[index];
      setEditingParamIndex(index);
      paramForm.setFieldsValue({
        name: param.name,
        type: param.type,
        required: param.required || false,
        description: param.description || '',
      });
    } else {
      setEditingParamIndex(null);
      paramForm.resetFields();
    }
    setParamModalVisible(true);
  };

  const handleSaveParameter = async () => {
    try {
      const values = await paramForm.validateFields();
      const newParam: PluginParameter = {
        name: values.name.trim(),
        type: values.type,
        required: values.required || false,
        description: values.description?.trim() || undefined,
      };

      if (editingParamIndex !== null) {
        const updated = [...parameters];
        updated[editingParamIndex] = newParam;
        setParameters(updated);
      } else {
        setParameters([...parameters, newParam]);
      }

      setParamModalVisible(false);
      paramForm.resetFields();
      setEditingParamIndex(null);
      message.success(t('plugin.parameterSaved'));
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleDeleteParameter = (index: number) => {
    const updated = parameters.filter((_, i) => i !== index);
    setParameters(updated);
    message.success(t('plugin.parameterDeleted'));
  };

  const handleCancelParamModal = () => {
    setParamModalVisible(false);
    paramForm.resetFields();
    setEditingParamIndex(null);
  };

  const getTypeColor = (type: string) => {
    const colorMap: Record<string, string> = {
      string: 'blue',
      number: 'green',
      boolean: 'orange',
      object: 'purple',
    };
    return colorMap[type] || 'default';
  };

  return (
    <Card title={isEdit ? 'Edit Plugin' : 'Create Plugin'}>
      <ProForm
        form={form}
        initialValues={initialValues}
        onFinish={handleSubmit}
        loading={loading}
        submitter={{
          searchConfig: {
            submitText: isEdit ? 'Update' : 'Create',
          },
          resetButtonProps: {
            onClick: () => navigate('/plugins'),
          },
        }}
      >
        <Tabs
          defaultActiveKey="basic"
          items={[
            {
              key: 'basic',
              label: t('plugin.basicInfo'),
              children: (
                <>
                  <ProFormText
                    name="name"
                    label={t('plugin.name')}
                    placeholder={t('plugin.namePlaceholder')}
                    rules={[{ required: true, message: t('plugin.nameRequired') }]}
                  />

                  <ProFormTextArea
                    name="description"
                    label={t('plugin.description')}
                    placeholder={t('plugin.descriptionPlaceholder')}
                    fieldProps={{ rows: 4 }}
                  />

                  <ProFormSelect
                    name="pluginType"
                    label={t('plugin.type')}
                    options={[
                      { label: 'MCP', value: 'MCP' },
                      { label: 'OpenAPI', value: 'OpenAPI' },
                    ]}
                    rules={[{ required: true, message: t('plugin.typeRequired') }]}
                    placeholder={t('plugin.typePlaceholder')}
                    initialValue="MCP"
                  />

                  <ProFormSelect
                    name="authMethod"
                    label={t('plugin.authMethod')}
                    options={[
                      { label: t('plugin.authNone'), value: 'none' },
                      { label: t('plugin.authBearer'), value: 'bearer' },
                      { label: t('plugin.authApiKey'), value: 'api_key' },
                      { label: t('plugin.authBasic'), value: 'basic' },
                    ]}
                    rules={[{ required: true, message: t('plugin.authMethodRequired') }]}
                    placeholder={t('plugin.authMethodPlaceholder')}
                    initialValue="none"
                  />

                  <ProFormText
                    name="endpoint"
                    label={t('plugin.endpoint')}
                    placeholder="https://api.example.com/plugin"
                    rules={[{ type: 'url', message: t('plugin.endpointInvalid') }]}
                    tooltip={t('plugin.endpointTooltip')}
                  />
                </>
              ),
            },
            {
              key: 'parameters',
              label: t('plugin.parameters'),
              children: (
                <>
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Text type="secondary">
                        {parameters.length > 0
                          ? `${t('plugin.totalParameters')}: ${parameters.length}`
                          : t('plugin.noParameters')}
                      </Text>
                      <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => handleOpenParamModal()}
                      >
                        {t('plugin.addParameter')}
                      </Button>
                    </div>

                    {parameters.length === 0 ? (
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={t('plugin.noParametersDescription')}
                        style={{ padding: '40px 0' }}
                      />
                    ) : (
                      <List
                        bordered
                        dataSource={parameters}
                        renderItem={(param, index) => (
                          <List.Item
                            style={{
                              padding: '16px 24px',
                              transition: 'background-color 0.3s',
                              cursor: 'pointer',
                            }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.backgroundColor = '#fafafa';
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.backgroundColor = 'transparent';
                            }}
                            actions={[
                              <Button
                                key="edit"
                                type="text"
                                icon={<EditOutlined />}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleOpenParamModal(index);
                                }}
                              >
                                {t('common.edit')}
                              </Button>,
                              <Button
                                key="delete"
                                type="text"
                                danger
                                icon={<DeleteOutlined />}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleDeleteParameter(index);
                                }}
                              >
                                {t('common.delete')}
                              </Button>,
                            ]}
                            onClick={() => handleOpenParamModal(index)}
                          >
                            <List.Item.Meta
                              avatar={
                                <div
                                  style={{
                                    width: 40,
                                    height: 40,
                                    borderRadius: '8px',
                                    backgroundColor: '#52c41a',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    color: '#fff',
                                    fontSize: '18px',
                                    fontWeight: 'bold',
                                  }}
                                >
                                  {index + 1}
                                </div>
                              }
                              title={
                                <Space size="middle">
                                  <Text strong style={{ fontSize: '16px' }}>
                                    {param.name}
                                  </Text>
                                  <Tag color={getTypeColor(param.type)}>
                                    {param.type.toUpperCase()}
                                  </Tag>
                                  {param.required && (
                                    <Tag color="red">{t('plugin.required')}</Tag>
                                  )}
                                </Space>
                              }
                              description={
                                param.description && (
                                  <div style={{ marginTop: '8px' }}>
                                    <Text type="secondary" style={{ fontSize: '13px' }}>
                                      {param.description}
                                    </Text>
                                  </div>
                                )
                              }
                            />
                          </List.Item>
                        )}
                      />
                    )}
                  </Space>

                  <Modal
                    title={editingParamIndex !== null ? t('plugin.editParameter') : t('plugin.addParameter')}
                    open={paramModalVisible}
                    onOk={handleSaveParameter}
                    onCancel={handleCancelParamModal}
                    width={600}
                    okText={t('common.save')}
                    cancelText={t('common.cancel')}
                  >
                    <Form
                      form={paramForm}
                      layout="vertical"
                      initialValues={{
                        name: '',
                        type: 'string',
                        required: false,
                        description: '',
                      }}
                    >
                      <Form.Item
                        name="name"
                        label={t('plugin.parameterName')}
                        rules={[{ required: true, message: t('plugin.parameterNameRequired') }]}
                      >
                        <Input placeholder={t('plugin.parameterNamePlaceholder')} />
                      </Form.Item>
                      <Form.Item
                        name="type"
                        label={t('plugin.parameterType')}
                        rules={[{ required: true, message: t('plugin.parameterTypeRequired') }]}
                      >
                        <Select>
                          <Select.Option value="string">String</Select.Option>
                          <Select.Option value="number">Number</Select.Option>
                          <Select.Option value="boolean">Boolean</Select.Option>
                          <Select.Option value="object">Object</Select.Option>
                        </Select>
                      </Form.Item>
                      <Form.Item name="required" valuePropName="checked">
                        <Checkbox>{t('plugin.parameterRequired')}</Checkbox>
                      </Form.Item>
                      <Form.Item
                        name="description"
                        label={t('plugin.parameterDescription')}
                      >
                        <Input.TextArea
                          rows={3}
                          placeholder={t('plugin.parameterDescriptionPlaceholder')}
                        />
                      </Form.Item>
                    </Form>
                  </Modal>
                </>
              ),
            },
          ]}
        />
      </ProForm>
    </Card>
  );
};

export default PluginForm;
